package com.wan37.logic.fighting;

import com.wan37.logic.domain.vo.SkillVO;
import com.wan37.logic.fighting.auto.AutoSkillServiceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 延迟线程池工具
 *
 * @author : luoyong
 * @date : 2020-06-10 17:21
 **/
@Component
public class SkillDelayThreadPool {

    @Autowired
    private AutoSkillServiceManager autoSkillServiceManager;

    /**
     * 延迟线程池
     */
    private static ScheduledExecutorService poll = new ScheduledThreadPoolExecutor(5);

    /**
     * 初始化的插入，延迟时间为0，直接将技能全部放入
     *
     * @param allRoleId
     * @param skillVO
     */
    public void initAdd(String allRoleId, SkillVO skillVO) {
        add(allRoleId, skillVO, 0);
    }

    /**
     * 通过技能CD时间之后的插入技能优先级别队列
     *
     * @param allRoleId
     * @param skillVO
     */
    public void add(String allRoleId, SkillVO skillVO) {
        add(allRoleId, skillVO, skillVO.getCD());
    }

    /**
     * 提交任务
     *
     * @param allRoleId
     * @param skillVO
     * @param delay
     */
    public void add(String allRoleId, SkillVO skillVO, long delay) {
        /**
         * 可释放的优先级别队列里面没有技能则在延迟时间之后插入技能
         */
        if (!AutoSkillServiceManager.allRoleIdToPBQMap.get(allRoleId).contains(skillVO)) {
            poll.schedule(() -> {
                autoSkillServiceManager.addPbqSkill(allRoleId, skillVO);
            }, delay, TimeUnit.SECONDS);
        }
    }
}
